package com.dylan.历史.eventbus;

import com.google.common.eventbus.AsyncEventBus;
import com.google.common.eventbus.EventBus;
import org.apache.commons.lang3.time.DateFormatUtils;

import java.util.Date;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author : ankang
 * @date : 2020/12/12 14:22
 * @Description :
 */
public class EventBusTest {



    public static void main(String[] args) {
        /*
        1. 完全异步发送

         */
        BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>(20);
        ThreadPoolExecutor executor = new ThreadPoolExecutor(4, 4,
                30, TimeUnit.SECONDS, workQueue);
        AsyncEventBus eventBus = new AsyncEventBus(executor);
        eventBus.register(new EventListener("---"));
        eventBus.register(new EventListener("************"));
        for (int i = 0; i < 100; i++) {
            System.out.println("发送开始:" + DateFormatUtils.format(new Date(), "HH:mm:ss.SSS"));
            eventBus.post(new MyEvent(i, new Date()));
            System.out.println("发送结束:" + DateFormatUtils.format(new Date(), "HH:mm:ss.SSS"));
        }
    }

    public void testBus() {
        /*
        1. 同步bus，一个消费完毕，才能发送下一个
        2. 多个listener时，会顺序同步消费
         */
        EventBus eventBus = new EventBus();
        eventBus.register(new EventListener("---"));
        eventBus.register(new EventListener("************"));
        for (int i = 0; i < 100; i++) {
            System.out.println("发送开始:" + DateFormatUtils.format(new Date(), "HH:mm:ss.SSS"));
            eventBus.post(new MyEvent(i, new Date()));
            System.out.println("发送结束:" + DateFormatUtils.format(new Date(), "HH:mm:ss.SSS"));
        }
    }
}
